package com.feigu.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class JSONUtils {

    private static final Logger log = LoggerFactory.getLogger(JSONUtils.class);

    final static ObjectMapper objectMapper;


    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
    @SuppressWarnings("unchecked")
    public static <T> T json2GenericObject(String jsonString, TypeReference<T> tr) {
        if (jsonString == null || "".equals(jsonString)) {
            return null;
        } else {
            try {
                return (T) objectMapper.readValue(jsonString, tr);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }




    @SuppressWarnings("deprecation")
    public static String toJson(Object object) {
        String jsonString = "";
        try {
           jsonString = objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return jsonString;

    }


    public static <T> List<T> toList(String jsonString,Class<T> tClass){
        try {
            if (jsonString == null || "".equals(jsonString)) {
                return null;
            }
            return (List<T>)objectMapper.readValue(jsonString, getCollectionType(List.class, tClass));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static <T> T toObject(String jsonString, Class<T> c) {

        if (jsonString == null || "".equals(jsonString)) {
            return null;
        } else {
            try {
                return objectMapper.readValue(jsonString, c);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public static <T> T toObject(Map<String,Object> map,Class<T> c){
        return JSONUtils.toObject(JSONUtils.toJson(map),c);
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

}
